import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'globals.dart' as globals;
import 'calendar_popup_view.dart';
//TODO:详细剖析热门帖子 and 传入不同的热点id
class HotSpotPage extends StatefulWidget {
  @override
  _HotSpotPageState createState() => _HotSpotPageState();
}

class _HotSpotPageState extends State<HotSpotPage> {
  DateTime startDate = DateTime.now();
  DateTime endDate = DateTime.now().add(const Duration(days: 5));
  List<String> titles = [
    '每日穿搭', 'ootd每日穿搭','小个子穿搭', '今天穿什么香', '穿搭技巧',
    '显瘦穿搭', '平价穿搭', '梨形身材', '夏日穿搭', '明星穿搭'
  ];
  List<String> postNums = [
    '53246', '51415', '49853', '42314',
    '38090', '33456', '30231', '27843', '24542','20127'
  ];

  List<String> urls = [
    'lib/images/littleDressing.jpg',
    'lib/images/dressingImage5.jpg',

    'lib/images/dressingTech.png',
    'lib/images/starDressing.jpg',
    'lib/images/pic1.png',






    'lib/images/dressingImage2.png',
    'lib/images/dressingImage4.png',
    'lib/images/dressingImage3.png',

    'lib/images/dressingImage1.png',

    'lib/images/dailyDressing.png',


    // 其他 URL ...
  ];



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Row(
          children: [
            Text(
              '热点推荐',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(width: 8.0),
            Icon(Icons.location_on),
          ],
        ),
      ),
      body: Column(
        children: [
          Container(
            color: Colors.grey[200],
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.all(13.0),
                  child: Material(
                    elevation: 4.0,
                    borderRadius: BorderRadius.circular(40.0),
                    color: Colors.white,
                    child: Row(
                      children: [
                        Expanded(
                          child: SizedBox(
                            width: 40.0,
                            child: TextField(
                              decoration: InputDecoration(
                                hintText: '梨形身材',
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.only(left: 16.0, right: 32.0),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 8.0),
                        FloatingActionButton(
                          onPressed: () {
                            // Handle search button press
                          },
                          backgroundColor: Color(0xFF51CCBB),
                          child: Icon(Icons.search),
                          shape: CircleBorder(),
                        ),
                      ],
                    ),
                  ),
                ),
                getTimeDateUI(),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 20.0, top: 10.0),
            child: Row(
              children: [
                Text(
                  '找到281条热点',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Spacer(),
                Text(
                  '筛选',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(width: 5.0),
                Padding(
                  padding: const EdgeInsets.only(right: 25.0),
                  child: Icon(Icons.filter_list, color: Color(0xFF51CCBB)),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: 10,
              itemBuilder: (context, index) {
                String title = titles[index];
                String postnum = postNums[index];
                String url = urls[index];
                return CustomCard(
                  title: title,
                  subtitle: '参与帖数 $postnum',
                  imageUrl: url,
                  onTap: () {
                    // Handle tap on the card
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget getTimeDateUI() {
    return Padding(
      padding: const EdgeInsets.only(left: 18, bottom: 16),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Row(
              children: <Widget>[
                Material(
                  color: Colors.transparent,
                  child: InkWell(
                    focusColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    hoverColor: Colors.transparent,
                    splashColor: Colors.grey.withOpacity(0.2),
                    borderRadius: const BorderRadius.all(
                      Radius.circular(4.0),
                    ),
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      showDemoDialog(context: context);
                    },
                    child: Padding(
                      padding: const EdgeInsets.only(
                          left: 8, right: 8, top: 4, bottom: 4),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            '日期',
                            style: TextStyle(
                                fontWeight: FontWeight.w100,
                                fontSize: 16,
                                color: Colors.grey.withOpacity(0.8)),
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          Text(
                            '${DateFormat("dd, MMM").format(startDate)} - ${DateFormat("dd, MMM").format(endDate)}',
                            style: TextStyle(
                                color: Colors.black,
                              fontWeight: FontWeight.w100,
                              fontSize: 16,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(right: 8),
            child: Container(
              width: 1,
              height: 42,
              color: Colors.grey.withOpacity(0.8),
            ),
          ),
          Expanded(
            child: Row(
              children: <Widget>[
                Material(
                  color: Colors.transparent,
                  child: InkWell(
                    focusColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    hoverColor: Colors.transparent,
                    splashColor: Colors.grey.withOpacity(0.2),
                    borderRadius: const BorderRadius.all(
                      Radius.circular(4.0),
                    ),
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                    },
                    child: Padding(
                      padding: const EdgeInsets.only(
                          left: 8, right: 8, top: 4, bottom: 4),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            '主题',
                            style: TextStyle(
                                fontWeight: FontWeight.w100,
                                fontSize: 16,
                                color: Colors.grey.withOpacity(0.8)),
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          Text(
                            '日常穿搭',
                            style: TextStyle(
                              fontWeight: FontWeight.w100,
                              fontSize: 16,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void showDemoDialog({BuildContext? context}) {
    showDialog<dynamic>(
      context: context!,
      builder: (BuildContext context) => CalendarPopupView(
        barrierDismissible: true,
        minimumDate: DateTime.now(),
        initialEndDate: endDate,
        initialStartDate: startDate,
        onApplyClick: (DateTime startData, DateTime endData) {
          setState(() {
            startDate = startData;
            endDate = endData;
          });
        },
        onCancelClick: () {},
      ),
    );
  }
}
int hotspotId=1;
class CustomCard extends StatefulWidget {
  final String title;
  final String subtitle;
  final String imageUrl;
  final Function onTap;

  CustomCard({
    required this.title,
    required this.subtitle,
    required this.imageUrl,
    required this.onTap,
  });

  @override
  _CustomCardState createState() => _CustomCardState();
}

class _CustomCardState extends State<CustomCard> {
  bool isFavorited = false;


  void _showPostDetailsDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(
            "热点详情",
            style: TextStyle(fontWeight: FontWeight.bold), // 加粗
          ),
          content: SizedBox(
            height: 300, // 设定弹窗的最大高度
            child: FutureBuilder<List<Post>>(
              future: fetchHotspotDetails(hotspotId), // 传入您的热点话题 id
              //后续需变换id
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  // 如果正在加载数据，显示加载指示器
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                } else if (snapshot.hasError) {
                  // 如果发生错误，显示错误消息
                  return Center(
                    child: Text('Error: ${snapshot.error}'),
                  );
                } else if (snapshot.hasData) {
                  // 如果成功获取到数据，显示帖子内容
                  final List<Post> posts = snapshot.data!;
                  return SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: posts.map((post) {
                        return Padding(
                          padding: EdgeInsets.symmetric(vertical: 8.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                post.title,
                                style: TextStyle(
                                  fontSize: 18.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              SizedBox(height: 4.0),
                              Text(
                                '链接: ${post.link}',
                                style: TextStyle(
                                  fontSize: 15.0,
                                ),
                              ),
                              Text(
                                '点赞量: ${post.likeCount}, 收藏量: ${post.collectionCount}, 评论量: ${post.commentCount}',
                                style: TextStyle(
                                  fontSize: 14.0,
                                ),
                              ),
                              SizedBox(height: 8.0),
                              Divider(), // 分隔线
                            ],
                          ),
                        );
                      }).toList(),
                    ),
                  );
                } else {
                  // 如果没有数据，显示“没有数据”的文本
                  return Center(
                    child: Text('No data'),
                  );
                }
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Close'),
            ),
          ],
        );
      },
    );
  }



  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 500),
      curve: Curves.easeInOut,
      margin: EdgeInsets.symmetric(horizontal: 15.0, vertical: 4.0),
      child: InkWell(
        onTap: _showPostDetailsDialog,
        child: Card(
          elevation: 4.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(20.0),
            child: _buildFrontContent(),
          ),
        ),
      ),
    );
  }

  Widget _buildFrontContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Image.asset(
          widget.imageUrl,
          height: 150,
          fit: BoxFit.fill,
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.title,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 4.0),
              Text(
                widget.subtitle,
                style: TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ),
      ],
    );
  }
}



Future<List<Post>> fetchHotspotDetails(int id) async {
  try {
    hotspotId++;
    final url = Uri.parse('${globals.url}/hotspots/fetchDetails?id=$id');
    print(globals.token);
    var headers = {
      "token": globals.token ?? "",
      "Content-Type": "application/json",
    };
    var response = await http.get(url, headers: headers);
    if (response.statusCode == 200) {
      final responseData = jsonDecode(const Utf8Decoder().convert(response.bodyBytes));
      if (responseData['code'] == 200) {
        List<Post> posts = [];
        responseData['data'].forEach((post) {
          posts.add(Post.fromJson(post));
        });
        return posts;
      } else {
        print('操作失败: ${responseData['msg']}');
        throw Exception('操作失败: ${responseData['msg']}');
      }
    } else {
      print('HTTP Error!!: ${response.statusCode}');
      throw Exception('HTTP Error!!: ${response.statusCode}');
    }
  } catch (err) {
    print('Error fetching hotspot details: $err');
    throw Exception('Error fetching hotspot details: $err');
  }
}
class Post {
  final int postId;
  final int hotSpotId;
  final String link;
  final String title;
  final int likeCount;
  final int collectionCount;
  final int commentCount;

  Post({
    required this.postId,
    required this.hotSpotId,
    required this.link,
    required this.title,
    required this.likeCount,
    required this.collectionCount,
    required this.commentCount,
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      postId: json['post_id'],
      hotSpotId: json['hotSpot_id'],
      link: json['link'],
      title: json['title'],
      likeCount: json['likeCount'],
      collectionCount: json['collectionCount'],
      commentCount: json['commentCount'],
    );
  }
}